package com.yixun.controller;

import com.alibaba.fastjson.JSONObject;
import com.yixun.entity.YxUser;
import com.yixun.mapper.UserMapper;
import com.yixun.mapper.WxMapper;
import com.yixun.util.Const;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author lbx create by 2021/6/30 10:00
 * @apiNote WxController
 */
@Controller
public class WxController extends BaseController {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;
    @Resource
    private WxMapper wxMapper;
    @Resource
    private UserMapper userMapper;
    @GetMapping("wxIndex")
    public String getTest(String code, HttpSession session, Model model) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = httpExtracted(url);
        String openid = (String) jsonObject.get("openid");
        /*login并绑定微信，下次进入免登录*/
        YxUser user = wxMapper.getUserByOpenid(openid);
        if (user != null) {
            session.setAttribute(Const.SESSION_USER, user);
            return "wechat/wxIndex";
        } else {
            model.addAttribute("openid", openid);
            return "wechat/login";
        }
    }
    
    @GetMapping("bingWx")
    @ResponseBody
    public Integer bindWx(String openid) {
        YxUser yxUser = this.getSessionUser();
        yxUser.setOpenId(openid);
        return userMapper.updateUser(yxUser);
    }
    
    @GetMapping("goIndex")
    public String goIndex() {
        return "wechat/wxIndex";
    }
    
    private JSONObject httpExtracted(String url) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String string = EntityUtils.toString(responseEntity);
                return JSONObject.parseObject(string);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
}
